package com.app.controller;

import com.app.mapper.ShareCircleAtlasMapper;
import com.app.mapper.ShareCircleMapper;
import com.app.mapper.ShareLikesComMapper;
import com.app.model.ShareCircleAtlasModel;
import com.app.model.ShareCircleModel;
import com.app.model.ShareLikesComModel;
import com.app.model.UserModel;
import com.app.service.ShareCircleAtlasService;
import com.app.service.ShareCircleService;
import com.app.service.ShareLikesComService;
import com.app.service.UserService;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.StringTool;
import com.app.util.TokenUtils;
import com.app.vo.ShareCircleVo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


@Controller
@RestController
public class ShareCircleController {


    @Autowired
    public ShareCircleService shareCircleService;
    @Autowired
    public ShareCircleAtlasService shareCircleAtlasService;
    @Autowired
    public UserService userService;
    @Autowired
    public ShareCircleMapper shareCircleMapper;
    @Autowired
    public ShareCircleAtlasMapper shareCircleAtlasMapper;
    @Autowired
    public ShareLikesComMapper shareLikesComMapper;
    @Autowired
    public ShareLikesComService shareLikesComService;

    @PostMapping("addShare")
    public Result<Object> addShare(
            @RequestParam("content") String content,
            @RequestParam("type") int type,
            @RequestParam("imgList") String imgList,
            HttpServletRequest request
    ) {
        JSONObject json = new JSONObject();
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");

        }

        ShareCircleModel model = new ShareCircleModel();
        model.setUserId(user.getId());
        model.setContent(content);
        model.setType(type);
        model.setCrtTime(CommonHelp.getNowTimestamp());
        shareCircleService.insert(model);
        int gid = model.getId();
        int j = 0;
        if(StringTool.isNotEmpty(imgList))
        {
            String[] imgArr = imgList.split(",");//获取图片集合字符串
            for (int i = 0; i < imgArr.length; i++) {
                ShareCircleAtlasModel sa = new ShareCircleAtlasModel();
                sa.setSid(gid);
                sa.setImgUrl(imgArr[i]);

                FileNameMap fileNameMap = URLConnection.getFileNameMap();
                String contentTypeFor = fileNameMap.getContentTypeFor(sa.getImgUrl());
                if (contentTypeFor != null) {// 当是图片时不为空，是视频时为空
                    j = 1;
                }
                if (j == 1) {
                    sa.setUploadType(1);
                } else {
                    sa.setUploadType(2);
                }
                shareCircleAtlasService.insert(sa);
            }
        }
        return Result.success(null);
    }

    @RequestMapping(value = "delById", method = RequestMethod.GET)
    public Result<Object> delShareById(int id) {
        JSONObject json = new JSONObject();
        try {
            if (id > 0) {
                shareCircleService.delete(id);
            } else {
                return Result.error(500,"ID不存在");

            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return Result.success(null);
    }

    @RequestMapping("getShareCircle")
    public Object getShareCircle(@RequestParam("circleType") Integer circleType,
                                 HttpServletRequest request
    ) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        int page  = Integer.valueOf(request.getParameter("page"));
        int limit = Integer.valueOf(request.getParameter("limit"));
        ShareCircleModel model = new ShareCircleModel();
        model.setPage((page - 1) * limit);
        model.setLimit(limit);
      if (circleType == 2) {

          model.setUserId(user.getId());
        }
        //全查职友圈
        List<ShareCircleModel> circleList = shareCircleMapper.selectCircleAll(model);
        ShareCircleVo shareCircleVo = new ShareCircleVo();
        Integer total = circleList.size();
        shareCircleVo.setCount(total);
        for (int i = 0; i < circleList.size(); i++) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Timestamp data1 = Timestamp.valueOf(String.valueOf(circleList.get(i).getCrtTime()));//开始时间
            String str = new SimpleDateFormat("yyyy-MM-dd HH:mm ").format(data1);
            circleList.get(i).setFormatTime(str);
            if(circleList.get(i).getRealName().length() == 2){
                String starName = circleList.get(i).getRealName().substring(0,1) +"*" ;
                circleList.get(i).setRealName(starName);
            }else{
                String starName = circleList.get(i).getRealName().substring(0,1) +"**" ;
                circleList.get(i).setRealName(starName);
            }
            ShareLikesComModel LikesComModel = shareLikesComService.findIsLikes(circleList.get(i).getId(),user.getId());
            if(LikesComModel==null){
                circleList.get(i).setSentry(2);
            }else {
                circleList.get(i).setSentry(1);
            }
            Integer likeCount = shareLikesComService.likeCount(circleList.get(i).getId());
            circleList.get(i).setLikeCount(likeCount);
            Integer tid = circleList.get(i).getId();
            List<ShareCircleAtlasModel> imgList = shareCircleAtlasService.selectImgBySid(tid);
            if(imgList == null){
                imgList= new ArrayList<>();
            }
            List<ShareCircleAtlasModel> videoList = shareCircleAtlasService.selectVideoBySid(tid);
            if(videoList== null){
                videoList= new ArrayList<>();
            }
            List<ShareLikesComModel> comList = shareLikesComMapper.selectShareByZid(tid);
            if(comList == null){
                comList= new ArrayList<>();
            }
            for (int j = 0; j < comList.size(); j++) {
                if(comList.get(j).getRealName().length() == 2){
                    String starName = comList.get(j).getRealName().substring(0,1) +"*" ;
                    comList.get(j).setStarName(starName);
                }else{
                    String starName = comList.get(j).getRealName().substring(0,1) +"**" ;
                    comList.get(j).setStarName(starName);
                }
            }
            circleList.get(i).setImgList(imgList);
            circleList.get(i).setVideoList(videoList);
            circleList.get(i).setShareLikesComList(comList);
            shareCircleVo.setModelList(circleList);
        }
        return Result.success(shareCircleVo);
    }
    @RequestMapping(value = "findComById", method = RequestMethod.GET)
    public Result<Object> findComById(int id,
                               HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String mobile = TokenUtils.verify(token);
        UserModel user = userService.getUserByMobile(mobile);
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
       List<ShareLikesComModel> comList = shareLikesComService.selectComById(id);
        if(comList.size()<0){
            return Result.success(null);
        }else {
            return Result.success(comList);
        }
    }
}

